import os
import sys

# 添加项目根目录到Python路径，以便导入config_reader模块
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(os.path.dirname(current_dir))
sys.path.append(project_root)

from config_reader import get_deepseek_api_key, get_openai_api_key
from mem0 import Memory

# 从配置文件读取API密钥
deepseek_api_key = get_deepseek_api_key()
openai_api_key = get_openai_api_key()

# 设置环境变量
os.environ["DEEPSEEK_API_KEY"] = deepseek_api_key
os.environ["OPENAI_API_KEY"] = openai_api_key  # for embedder model

config = {
    ## 使用 Chroma 本地向量数据库
    "vector_store": {
        "provider": "Chroma",
        "config": {
            "collection_name": "test_mem0_demo",
            "path": "chroma_db"  # 本地存储目录
        }
    },
    # deepseek model
    "llm": {
        "provider": "deepseek",
        "config": {
            "model": "deepseek-chat",  
            "temperature": 0.2,
            "max_tokens": 2000,
            "top_p": 1.0
        }
    },
    # 使用 OpenAI 作为嵌入模型
    "embedder": {
        "provider": "openai",  
        "config": {
            "model": "text-embedding-ada-002",
            "api_key": openai_api_key
        }
    }
}

try:
    print("正在初始化 Memory...")
    m = Memory.from_config(config)
    print("Memory 初始化成功！")
    
    messages = [
        {"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
        {"role": "assistant", "content": "How about a thriller movies? They can be quite engaging."},
        {"role": "user", "content": "I'm not a big fan of thriller movies but I love sci-fi movies."},
        {"role": "assistant",
         "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
    ]
    
    print("正在添加消息到记忆...")
    m.add(messages, user_id="alice", metadata={"category": "movies"})
    print("消息添加成功！")
    
    # 测试查询
    print("正在测试查询...")
    results = m.query("What kind of movies does the user like?", user_id="alice")
    print(f"查询结果：{results}")
    
    # 测试记忆检索
    print("\n正在测试记忆检索...")
    retrieved_messages = m.get(user_id="alice", limit=5)
    print(f"检索到的消息数量：{len(retrieved_messages)}")
    for i, msg in enumerate(retrieved_messages):
        print(f"消息 {i+1}: {msg['content'][:100]}...")
    
except Exception as e:
    print(f"错误：{e}")
    import traceback
    traceback.print_exc()
